package com.imgrate.migration.controller;

import com.imgrate.migration.entity.MigrationTask;
import com.imgrate.migration.entity.Server;
import com.imgrate.migration.service.MigrationService;
import com.imgrate.migration.service.ServerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@RestController
@RequestMapping("/migrations")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class MigrationController {
    
    private final MigrationService migrationService;
    private final ServerService serverService;
    
    // 注入应用的异步执行器
    private final Executor taskExecutor;
    
    @PostMapping
    public ResponseEntity<MigrationTask> createMigrationTask(@RequestBody MigrationTask task) {
        try {
            MigrationTask createdTask = migrationService.createMigrationTask(task);
            return ResponseEntity.ok(createdTask);
        } catch (Exception e) {
            log.error("创建迁移任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping
    public ResponseEntity<List<MigrationTask>> getAllTasks() {
        List<MigrationTask> tasks = migrationService.getAllTasks();
        return ResponseEntity.ok(tasks);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<MigrationTask> getTaskById(@PathVariable Long id) {
        Optional<MigrationTask> task = migrationService.getTaskById(id);
        if (task.isPresent()) {
            return ResponseEntity.ok(task.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @PutMapping("/{id}/status")
    public ResponseEntity<MigrationTask> updateTaskStatus(
            @PathVariable Long id,
            @RequestParam String status,
            @RequestParam(required = false) Integer progress,
            @RequestParam(required = false) String errorMessage) {
        try {
            MigrationTask updatedTask = migrationService.updateTaskStatus(id, status, progress, errorMessage);
            return ResponseEntity.ok(updatedTask);
        } catch (Exception e) {
            log.error("更新任务状态失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}/reset")
    public ResponseEntity<MigrationTask> resetTask(@PathVariable Long id) {
        try {
            MigrationTask resetTask = migrationService.resetTask(id);
            return ResponseEntity.ok(resetTask);
        } catch (Exception e) {
            log.error("重置任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}/pause")
    public ResponseEntity<MigrationTask> pauseTask(@PathVariable Long id) {
        try {
            MigrationTask pausedTask = migrationService.pauseTask(id);
            return ResponseEntity.ok(pausedTask);
        } catch (Exception e) {
            log.error("暂停任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}/resume")
    public ResponseEntity<MigrationTask> resumeTask(@PathVariable Long id) {
        try {
            MigrationTask resumedTask = migrationService.resumeTask(id);
            return ResponseEntity.ok(resumedTask);
        } catch (Exception e) {
            log.error("恢复任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}/stop")
    public ResponseEntity<MigrationTask> stopTask(@PathVariable Long id) {
        try {
            MigrationTask stoppedTask = migrationService.stopTask(id);
            return ResponseEntity.ok(stoppedTask);
        } catch (Exception e) {
            log.error("停止任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
        try {
            migrationService.deleteTask(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("删除任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PostMapping("/{id}/execute")
    public ResponseEntity<String> executeMigration(@PathVariable Long id) {
        try {
            // 获取任务信息进行验证
            Optional<MigrationTask> taskOpt = migrationService.getTaskById(id);
            if (!taskOpt.isPresent()) {
                return ResponseEntity.badRequest().body("迁移任务不存在");
            }
            
            MigrationTask task = taskOpt.get();
            if (!"PENDING".equals(task.getStatus())) {
                return ResponseEntity.badRequest().body("任务状态不正确，只有待执行的任务才能启动");
            }
            
            // 验证源服务器和目标服务器是否存在
            if (task.getSourceServerId() == null || task.getTargetServerId() == null) {
                return ResponseEntity.badRequest().body("源服务器或目标服务器信息不完整");
            }
            
            Optional<Server> sourceServerOpt = serverService.getServerById(task.getSourceServerId());
            Optional<Server> targetServerOpt = serverService.getServerById(task.getTargetServerId());
            
            if (!sourceServerOpt.isPresent() || !targetServerOpt.isPresent()) {
                return ResponseEntity.badRequest().body("源服务器或目标服务器不存在");
            }
            
            // 异步执行迁移任务，立即返回响应
            CompletableFuture.runAsync(() -> {
                try {
                    migrationService.executeMigration(id);
                } catch (Exception e) {
                    log.error("异步执行迁移任务失败: {}", e.getMessage(), e);
                }
            }, taskExecutor);
            
            return ResponseEntity.ok("迁移任务已启动");
        } catch (Exception e) {
            log.error("执行迁移任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body("执行迁移任务失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/status/{status}")
    public ResponseEntity<List<MigrationTask>> getTasksByStatus(@PathVariable String status) {
        List<MigrationTask> tasks = migrationService.getTasksByStatus(status);
        return ResponseEntity.ok(tasks);
    }
}